package com.fayuan.nocv.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fayuan.nocv.entity.NocvData;
import com.fayuan.nocv.service.IndexService;
import com.fayuan.nocv.vo.DataView;
import com.fayuan.nocv.vo.NocvDataVo;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/chinaMapManage")
public class ChinaMapManageController {

    @Autowired
    private IndexService indexService;
    @GetMapping("/PageList")
    @ResponseBody
    public DataView PageList(NocvDataVo nocvDataVo){

        IPage<NocvData>page = new Page<>(nocvDataVo.getPage(), nocvDataVo.getLimit());
        QueryWrapper<NocvData>wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("value");
        if (nocvDataVo.getName()!=null){
             wrapper.like("name",nocvDataVo.getName());
        }
        IPage<NocvData> page1 = indexService.page(page, wrapper);
        DataView dataView = new DataView(page1.getTotal(),page1.getRecords());
        return dataView;
    }
    @PostMapping("/deleteById")
    @ResponseBody
    public DataView removeById(Integer id){
        String name = indexService.getById(id).getName();
        boolean b = indexService.removeById(id);
        DataView dataView = new DataView();
        if (b){
            dataView.setCode(200);
            dataView.setMsg(name+"删除成功");
        }
        List<NocvData> list = indexService.list();
        Jedis jedis = new Jedis("127.0.0.1");
        for (NocvData data : list) {
            String s = JSONObject.toJSONString(data);
            jedis.lpush("nocvData",s);
        }
        return dataView;
    }
    @PostMapping("/save")
    @ResponseBody
    public DataView save(@RequestBody NocvData nocvData){
        DataView dataView = new DataView();
        QueryWrapper<NocvData>wrapper = new QueryWrapper<>();
        wrapper.eq("name",nocvData.getName());
        if (indexService.getOne(wrapper)!=null){
            dataView.setMsg(nocvData.getName()+"已经存在");
            return dataView;
        }
        boolean save = indexService.save(nocvData);

        if (save){
            dataView.setCode(200);
            dataView.setMsg(nocvData.getName()+"添加成功");

        }
        return dataView;
    }

    @PostMapping("/Update")
    @ResponseBody
    public DataView update( NocvData nocvData){

        boolean save = indexService.updateById(nocvData);
        DataView dataView = new DataView();
        if (save){
            dataView.setCode(200);
            dataView.setMsg(nocvData.getName()+"修改成功");

        }
        List<NocvData> list = indexService.list();
        Jedis jedis = new Jedis("127.0.0.1");
        for (NocvData data : list) {
            String s = JSONObject.toJSONString(data);
            jedis.lpush("nocvData",s);
        }
        return dataView;
    }
    @PostMapping("/fileImport")
    @ResponseBody
    public DataView excelImportChina(@RequestParam("file")MultipartFile file) throws IOException {
        DataView dataView = new DataView();

        if (file.isEmpty()){
            dataView.setMsg("文件不能为空");
        }
        //poi获取Excel表格解析数据
        XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
        XSSFSheet sheet = wb.getSheetAt(0);
        //定义一个程序集合接收文件中的数据
        List<NocvData> list = new ArrayList<>();
        XSSFRow row = null;
        //解析数据，存放到集合中
        for (int i = 0;i<sheet.getPhysicalNumberOfRows();i++){
            //定义实体
            NocvData nocvData = new NocvData();
            //每一行的数据，放到实体类里面
            row = sheet.getRow(i);
            //解析数据
            nocvData.setName(row.getCell(0).getStringCellValue());
            nocvData.setValue((int)row.getCell(1).getNumericCellValue());
            //循环插入数据
            list.add(nocvData);
        }
        indexService.saveBatch(list);
        dataView.setCode(200);
        dataView.setMsg("excel数据插入成功");
        return dataView;
    }

    @RequestMapping("/excelOutPortChina")
    public void excelOutPortChina(HttpServletResponse response) throws UnsupportedEncodingException {
        //查询数据库【查询所有，符合条件的数据】
        List<NocvData>list = indexService.list();
        //建立Excel对象，封装数据
        response.setCharacterEncoding("utf-8");
        //创建Excel对象
        XSSFWorkbook wb = new XSSFWorkbook();
        //创建sheet对象
        XSSFSheet sheet = wb.createSheet("中国疫情数据sheet");
        //创建表头
        XSSFRow xssfRow = sheet.createRow(0);
        xssfRow.createCell(0).setCellValue("城市名称");
        xssfRow.createCell(1).setCellValue("确诊数量");
        //遍历数据，封装Excel工作对象
        for (NocvData data:list){
            XSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()+1);
            dataRow.createCell(0).setCellValue(data.getName());
            dataRow.createCell(1).setCellValue(data.getValue());
        }
        //建立输出流，输出浏览器文件
        OutputStream os = null;
        //设置Excel名字
        response.setContentType("application/octet-stream;chartset-utf8");
        response.setHeader("Content-Disposition","attachment;filename="+new String("中国疫情数据表".getBytes(),"iso-8859-1")+".xlsx");
        try {
            //输出文件
            os = response.getOutputStream();
            wb.write(os);
            os.flush();
            //关闭输出流
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
